package 二叉树.二叉树的最大深度;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2022/3/29 20:48
 * @description:
 * @version:
 */

public class Solution {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.right = new TreeNode(0);
        root.left.left = new TreeNode(3);
        root.right = new TreeNode(4);
        root.right.left = new TreeNode(9);
        root.right.right = new TreeNode(5);
        root.left.left.left = new TreeNode(8);
       // root.right.right.right.val = 8;
        int i = maxDepth2(root);
        System.out.println(i);
        return;
    }
    //解法1 采取递归 深度优先遍历
    public static int maxDepth(TreeNode root){
        if(root == null){
            return 0;
        }else {
            int left = maxDepth(root.left);
            int right = maxDepth(root.right);
            return Math.max(left,right) + 1;
        }
    }


    //解法2 采取广度优先搜索遍历
    public static int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        //向队列的队尾添加根节点元素
        queue.offer(root);
        //用一个变量 ans 来维护拓展的次数，该二叉树的最大深度即为ans
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            //每次出队时要把当前层次的节点全部出队，所以ans就等于该二叉树的深度
            while (size > 0) {
                //从队列的队首出元素
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }
        return ans;
    }


    //这是通过层次遍历求出了二叉树中节点的总个数
    public static int nodeNum(TreeNode root){
        if (root == null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 0;
        while (queue.size() != 0){
            TreeNode node = queue.poll();
            if (node.left != null){
                queue.offer(node.left);
            }
            if (node.right != null){
                queue.offer(node.right);
            }
            ans++;
        }
        return ans;
    }
}
